// adapter/app1-adapter.js
import { BaseAdapter } from './base-adapter'

export class App1Adapter extends BaseAdapter {
  constructor() {
    super()
    this.platform = 'app1'
    this.supportedMethods = [
      'login', 'logout', 'getUserInfo', 'pay',
      'share', 'scan', 'getLocation', 'setTitle'
    ]
    this.bridge = window.App1JSBridge //注册调用原生的方法
  }

  isMatch() {
    // 通过UserAgent或全局对象检测
    return !!(window.App1JSBridge &&
      navigator.userAgent.includes('CompanyApp1'))
  }

  async init() {
    // 等待桥接就绪
    await this.waitForBridgeReady()
    console.log('App1适配器初始化完成')
  }

  waitForBridgeReady() {
    return new Promise((resolve) => {
      if (this.bridge && this.bridge.isReady) {
        resolve()
      } else {
        // 监听就绪事件
        document.addEventListener('App1BridgeReady', resolve)
        // 超时处理
        setTimeout(resolve, 1000)
      }
    })
  }

  async invoke(method, params = {}) {
    if (!this.supportedMethods.includes(method)) {
      throw new Error(`App1不支持方法: ${method}`)
    }

    return new Promise((resolve, reject) => {
      try {
        // App1的调用约定：回调函数方式
        this.bridge.callHandler(method, JSON.stringify(params), (response) => {
          try {
            const result = typeof response === 'string' ?
              JSON.parse(response) : response
            resolve(result)
          } catch (e) {
            resolve(response)
          }
        })
      } catch (error) {
        reject(new Error(`App1调用失败: ${error.message}`))
      }
    })
  }

  on(event, callback) {
    // App1的事件监听方式
    if (this.bridge && this.bridge.addEventListener) {
      this.bridge.addEventListener(event, callback)
    } else {
      document.addEventListener(`App1_${event}`, callback)
    }
  }

  async getDeviceInfo() {
    return await this.invoke('getDeviceInfo')
  }

  async getUserInfo() {
    return await this.invoke('getUserInfo')
  }

  // App1特定的快捷方法
  async setNavigationBar(title, color = '#000000') {
    return await this.invoke('setTitle', { title, color })
  }

  async showLoading(text = '加载中...') {
    return await this.invoke('showLoading', { text })
  }

  async hideLoading() {
    return await this.invoke('hideLoading')
  }
}